﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.Controllers.FrontEnd;
using System.Web.Mvc;
using Proggy.Data.Abstract;
using Proggy.Data.Entities;
using Newtonsoft.Json;
using Proggy.Web.Cms.Membership;
using Proggy.Web.Cms.Context;

namespace Proggy.Web.Cms.Controllers.BackEnd
{
    /// <summary>
    /// ~/Proggy/Data
    /// </summary>
    [ProggyBackEndAuthorize(MembershipConstants.RANDOM_DATA_EDITOR_GROUP_NAME)]
    public class RandomDataController : BackEndControllerBase
    {
        /// <summary>
        /// Data controller constructor
        /// </summary>
        /// <param name="repo"></param>
        public RandomDataController(IRandomDataRepository repo)
        {
            //
            this.DataRepository = repo;

            // set cats
            ViewBag.CategoriesList = DataRepository.RandomDataItems.Select(x => x.CategoryAlias).Distinct().ToList();

            // set json
            ViewBag.CategoriesJson =
                JsonConvert.SerializeObject((List<string>)ViewBag.CategoriesList);
            
        }

        /// <summary>
        /// Data repo
        /// </summary>
        public IRandomDataRepository DataRepository { get; set; }

        /// <summary>
        /// ~/Proggy/Data
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string categoryAlias)
        {
            //
            ViewBag.Title = "Random data";

            // get model
            var model = DataRepository.RandomDataItems;

            // create select
            var selectList = new List<SelectListItem>();

            // add first
            selectList.Add(new SelectListItem { Text = "[All categories]", Value = "", Selected = string.IsNullOrEmpty(categoryAlias) });

            // loop cats
            ((List<string>)ViewBag.CategoriesList).ForEach(x => selectList.Add(new SelectListItem
                {
                    Text = x,
                    Value = x,
                    Selected = (!string.IsNullOrEmpty(categoryAlias) && x == categoryAlias)
                }));

            // get select
            ViewBag.Categories = selectList;

            // check category
            if (!string.IsNullOrEmpty(categoryAlias))
            {
                model = model.Where(x => x.CategoryAlias.ToLower() == categoryAlias.ToLower());
                ViewBag.Title += " (" + categoryAlias + ")";

            }

            // final
            var finalModel = model.OrderBy(x => x.CategoryAlias).AsEnumerable();

            //
            return View(finalModel);
        }

        /// <summary>
        /// Create new random data item
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            ViewBag.IsCreate = true;
            var model = new RandomDataItem();
            return View("EditCreate", model);
        }

        /// <summary>
        /// Create new random data item (POST)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(RandomDataItem model)
        {
            ViewBag.IsCreate = true;
            string errorMsg = "";

            if (ModelState.IsValid)
            {
                if (this.DataRepository.GetCreateOk(model.RandomDataItemId, model.CategoryAlias, model.Value, MembershipContext.Current.CurrentMember.Username, ref errorMsg))
                {
                    return RedirectToAction("Index", new { success = 11, categoryAlias = model.CategoryAlias });
                }
            }

            ModelState.AddModelError("", errorMsg);
            return View("EditCreate", model);
        }

        /// <summary>
        /// Edit new random data item
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(string dataId)
        {
            ViewBag.IsCreate = false;
            var model = this.DataRepository.RandomDataItems.SingleOrDefault(x => x.RandomDataItemId == dataId);
            if (model == null)
            {
                return RedirectToAction("Index");
            }

            return View("EditCreate", model);
        }

        /// <summary>
        /// Edit new random data item (POST)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(RandomDataItem model, string dataId)
        {
            ViewBag.IsCreate = false;
            string errorMsg = "";

            if (ModelState.IsValid)
            {
                if (this.DataRepository.GetEditOk(model.RandomDataItemId, model.CategoryAlias, model.Value, MembershipContext.Current.CurrentMember.Username, ref errorMsg))
                {
                    return RedirectToAction("Index", new { success = 12, categoryAlias = model.CategoryAlias });
                }
            }

            ModelState.AddModelError("", errorMsg);
            return View("EditCreate", model);
        }

        /// <summary>
        /// Delete new random data item
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(string dataId)
        {
            return View(new RandomDataItem { RandomDataItemId = dataId });
        }

        /// <summary>
        /// Edit new random data item (POST)
        /// </summary>
        /// <param name="model"></param>
        /// <param name="dataId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(RandomDataItem model, string dataId)
        {
            this.DataRepository.Delete(model.RandomDataItemId);
            return RedirectToAction("Index", new { success = 13 });
        }

        /// <summary>
        /// Returns unique id string
        /// </summary>
        /// <returns></returns>
        [HttpGet, OutputCache(Duration = 0, NoStore = true)]
        public string GetUniqueId()
        {
            return Guid.NewGuid().ToString();
        }
    }
}
